import type { Router } from "vue-router";
import NProgress from "@/utils/npprogress";
import { initRouter, handleAliveRoute, findRouteByPath } from "../utils";
import { isUrl, storageSession, openLink } from "@pureadmin/utils";
import { sessionKey, type DataInfo } from "@/utils/auth";
import { useUserStore } from "@/stores/modules/user";
import { getConfig } from "@/config";
import { usePermissionStoreHook } from "@/stores/modules/permission";
import { useMultiTagsStoreHook } from "@/stores/modules/multiTags";

/** 路由白名单 */
const whiteList = ["/login"];

export function createPermissionGuard(router: Router) {
  router.beforeEach(async (to: toRouteType, _from, next) => {
    if (to.meta?.keepAlive) {
      const newMatched = to.matched;
      handleAliveRoute(newMatched, "add");
      // 页面整体刷新和点击标签页刷新
      if (_from.name === undefined || _from.name === "Redirect") {
        handleAliveRoute(newMatched);
      }
    }
    NProgress.start();
    if (_from.name === undefined) {
      const userInfo = storageSession().getItem<DataInfo<number>>(sessionKey);
      // console.log(
      //   _from.name,
      //   "来及刷新或者iframe？？？？",
      //   userInfo,
      //   "Cookies",
      //   Cookies.get("testor_token")
      // );
      if (userInfo) {
        // 刷新页面从 session storage取数据
        useUserStore().SET_USERNAME(
          storageSession().getItem<DataInfo<number>>(sessionKey)?.username ?? ""
        );
      }
      // else {
      //   // NOTE：针对新打开页签 session 不存在重新请求后端获取用户信息
      //   try {
      //     const u = await getUserInfo();
      //     console.log(u, "uuuuuuu");
      //   } catch (error) {
      //     console.log("🚀 ~ file: 路由拦截 ~ router.beforeEach ~ error", error);
      //   }
      // }
    }
    const userInfo = storageSession().getItem<DataInfo<number>>(sessionKey);
    // 跳转到外部链接
    const externalLink = isUrl(to?.name as string);
    if (!externalLink) {
      to.matched.some((item) => {
        if (!item.meta.title) return "";
        const Title = getConfig().Title;
        if (Title) document.title = `${item.meta.title} | ${Title}`;
        else document.title = item.meta.title as string;
      });
    }
    /** 如果已经登录并存在登录信息后不能跳转到路由白名单，而是继续保持在当前页面 */
    function toCorrectRoute() {
      whiteList.includes(to.fullPath) ? next(_from.fullPath) : next();
    }
    if (userInfo) {
      if (_from?.name) {
        // name为超链接
        if (externalLink) {
          openLink(to?.name as string);
          NProgress.done();
          next(false);
        } else {
          // 有用户信息的情况下，正常跳转路由
          toCorrectRoute();
        }
      } else {
        // 页面刷新的情况
        if (
          usePermissionStoreHook().wholeMenus.length === 0 &&
          to.path !== "/login"
        ) {
          initRouter().then((router: Router) => {
            if (!useMultiTagsStoreHook().getMultiTagsCache) {
              const { path } = to;
              const route = findRouteByPath(
                path,
                router.options.routes[0].children
              );
              // query、params模式路由传参数的标签页不在此处处理
              if (route && route.meta?.title) {
                useMultiTagsStoreHook().handleTags("push", {
                  path: route.path,
                  name: route.name,
                  meta: route.meta,
                });
              }
            }
            router.push(to.fullPath);
          });
        }
        toCorrectRoute();
      }
    } else {
      if (to.path !== "/login") {
        // if (whiteList.indexOf(to.path) !== -1) {
        //   next();
        // } else {
        //   next({ path: "/login" });
        // }
        location.href = "/kg-web/sso/login";
      } else {
        next();
      }
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });
}
